<?php
class User_Model_Users extends Zend_Db_Table_Abstract
{
	protected $_name = 'users';
	protected $_sequence = 'users_id_seq';
	
	public function getSequence() {
		return $this->_sequence;
	}
	
	public function getUsers() {
        $select = $this->_db->select()
                        ->from($this->_name)
                        ->order('username ASC')
                        ->order('date_created ASC');
                        
        $results = $this->getAdapter()->fetchAll($select);
		
        return $results;
	}
	
	public function findUsers($username,$fullname,$alias,$email,$date_created) {
        $select = $this->_db->select()
                        ->from($this->_name)
                        ->order('username ASC')
                        ->order('date_created ASC');
        if($username) {
			$select->where('lower(username) LIKE ?', '%'.$username.'%');
		}
		if($fullname) {
			$select->where('lower(fullname) LIKE ?', '%'.$fullname.'%');
		}
		if($alias) {
			$select->where('lower(alias) LIKE ?', '%'.$alias.'%');
		}
		if($email) {
			$select->where('lower(email) LIKE ?', '%'.$email.'%');
		}                
        if($date_created) {
        	$select->where('date_created = ?', $date_created);
        }
                        
        $results = $this->getAdapter()->fetchAll($select); 
        
        return $results;
	}

	public function getUserById($id,$selectUserCrafts=false)
	{
		$id = (int)$id;
		$row = $this->fetchRow('id = ' . $id);
		
		if (!$row) {
			return false;
		} else {
			
			$results = $row->toArray();
			
			if(true === $selectUserCrafts) {
				$usersCraftsDbTable = new User_Model_UsersCrafts();
				$usersCrafts = $usersCraftsDbTable->getUserCraftByUser($id);
				
				$results['id_sector'] = $usersCrafts['id_sector'];
				$results['id_craft'] = $usersCrafts['id_craft'];
			}
			
			return $results;
		}
	}

	public function addUser($username,$password,$fullname,$alias,$email,$phone,$date_created)
	{
		$data = array(
			'username'	=> $username, 
			'password'	=> $password,
			'fullname'	=> $fullname,
			'alias' => $alias,
			'email' => $email,
			'phone' => $phone,
			'date_created' 	=> $date_created,
		);
		$this->insert($data);
	}

	public function updateUser($id,$fullname,$alias,$email,$phone)
	{
		$data = array(
			'fullname' 	=> $fullname,
			'alias' 	=> $alias,
			'email' 	=> $email,
			'phone' 	=> $phone,
		);
		$this->update($data, 'id = '. $id);
	}

	public function deleteUser($id)
	{
		$this->delete('id =' . (int)$id);
	}

	public function isUniqueUserEmail($email)
	{
		$select = $this->select();
		$select->from($this->_name, 'COUNT(*) AS num')
		->where('email = ?', $email);

		return ($this->fetchRow($select)->num == 0) ? true : false;
	}
	
	public function isUniqueUserUsername($username)
	{
		$select = $this->select();
		$select->from($this->_name, 'COUNT(*) AS num')
		->where('username = ?', $username);

		return ($this->fetchRow($select)->num == 0) ? true : false;
	}

}